const sharp = require('sharp');
const fs = require('fs/promises');
const path = require('path');

/**
 * 压缩指定前缀的PNG图片
 * @param {string} inputDir - 输入目录路径
 * @param {string} outputDir - 输出目录路径
 * @param {string} prefix - 文件前缀，默认为'X'
 * @param {Object} options - 压缩选项
 * @param {number} options.quality - 压缩质量，范围0-100，默认85
 */
async function compressPrefixImages(inputDir, outputDir, prefix = 'X', options = {}) {
  try {
    await fs.access(inputDir);
  } catch (error) {
    console.error(`输入目录不存在: ${inputDir}`);
    return;
  }

  // 确保输出目录存在
  try {
    await fs.access(outputDir);
  } catch (error) {
    await fs.mkdir(outputDir, { recursive: true });
  }

  const files = await fs.readdir(inputDir);
  const pngFiles = files.filter(file => 
    file.startsWith(prefix) && 
    path.extname(file).toLowerCase() === '.png'
  );

  if (pngFiles.length === 0) {
    console.log(`没有找到前缀为 ${prefix} 的PNG文件`);
    return;
  }

  console.log(`找到 ${pngFiles.length} 个符合条件的PNG文件`);

  await Promise.all(pngFiles.map(async (file) => {
    const inputPath = path.join(inputDir, file);
    const outputPath = path.join(outputDir, file);
    
    const quality = Math.min(Math.max(options.quality || 85, 0), 100);
    console.log(`正在压缩 ${file}: 质量 = ${quality}`);

    await sharp(inputPath)
      .rotate()
      .withMetadata({ orientation: undefined })
      .png({
        quality: quality ? quality * 1 : 80,
        compressionLevel: 9,
        adaptiveFiltering: true
      })
      .toFile(outputPath);

    console.log(`已压缩: ${file}`);
  }));

  console.log('所有文件压缩完成！');
}

// 使用示例：
compressPrefixImages('../images', './images', 'nav', { quality: 70 });

